import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, Repository, UpdateResult } from 'typeorm';
import { Video } from '../video/video.entity';
import { UserSetting } from './userSetting.entity';
import DataBase from '../../config/database'
import { WxUser } from '../wxUser/wxUser.entity';
import { Concern } from '../concern/concern.entity';
import { UnConcern } from '../unconcern/unconcern.entity';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { EnumInternetCelebrityGroupIsInitEnum, EnumInternetCelebrityGroupTypeEnum } from '../internetCelebrityGroup/internetCelebrityGroup.enum';
import utils from 'src/common/utils';
import { system_wx_user } from 'src/setting';

@Injectable()
export class UserSettingService {
  constructor(
    @InjectRepository(UserSetting)
    private settingRepository: Repository<UserSetting>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(WxUser)
    private wxUserRepository: Repository<WxUser>,
    @InjectRepository(Concern)
    private concernRepository: Repository<Concern>,
    @InjectRepository(UnConcern)
    private unConcernRepository: Repository<UnConcern>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRepository: Repository<InternetCelebrityGroup>,
    
  ) {}

  findOne_by_key(wx_user: string, key: string): Promise<UserSetting> {
    return this.settingRepository.findOne({where:{key, wx_user: wx_user}});
  }

  getIDCard(){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(7)
      if(await this.internetCelebrityGroupRepository.findOne({where:{id_card: id}})){
        loop()
      }
    }
    loop()
    return id
  }

  getIDCard_WxUser(){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(6)
      if(await this.wxUserRepository.findOne({where:{id_card: id}})){
        loop()
      }
    }
    loop()
    return id
  }

  async create(shieId: UserSetting): Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let icGroupItem = new InternetCelebrityGroup()
      icGroupItem.create_time = new Date()
      icGroupItem.id_card = this.getIDCard()
      icGroupItem.name = utils.uuid()
      icGroupItem.type = EnumInternetCelebrityGroupTypeEnum.overseas
      icGroupItem.wx_user = shieId.wx_user
      icGroupItem.is_init = EnumInternetCelebrityGroupIsInitEnum.yes
      await this.internetCelebrityGroupRepository.createQueryBuilder(null, queryRunner)
        .insert()
        .into(InternetCelebrityGroup)
        .values(icGroupItem)
        .execute()
      await this.settingRepository.createQueryBuilder(null, queryRunner)
        .insert()
        .into(UserSetting)
        .values(shieId)
        .execute()
      //给用户生成id_card
      await this.wxUserRepository.createQueryBuilder(null, queryRunner)
        .update({id_card: this.getIDCard_WxUser()})
        .where({openid: shieId.wx_user})
        .execute()
      
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async update(wx_user: string, key: string, value: string): Promise<any> {
    let findIc = await this.internetCelebrityGroupRepository.findOne({where:{wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas}})
    //查询用户信息
    let findWxUser = await this.wxUserRepository.findOne({where:{openid: wx_user}})
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      console.log(findIc,'findIc')
      if(!findIc){
        let icGroupItem = new InternetCelebrityGroup()
        icGroupItem.create_time = new Date()
        icGroupItem.id_card = this.getIDCard()
        icGroupItem.name = utils.uuid()
        icGroupItem.type = EnumInternetCelebrityGroupTypeEnum.overseas
        icGroupItem.wx_user = wx_user
        icGroupItem.is_init = EnumInternetCelebrityGroupIsInitEnum.yes
        await this.internetCelebrityGroupRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(InternetCelebrityGroup)
          .values(icGroupItem)
          .execute()
      }
      await this.settingRepository.createQueryBuilder(null, queryRunner)
        .update({value: value})
        .where({wx_user: wx_user, key: key})
        .execute()

      if(wx_user != system_wx_user || (findWxUser && !findWxUser.id_card)){
        //给用户生成id_card
        await this.wxUserRepository.createQueryBuilder(null, queryRunner)
          .update({id_card: this.getIDCard_WxUser()})
          .where({openid: wx_user})
          .execute()
      }
      
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
    
  }

  
  async changeOverseas(wx_user: string, value: string): Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    //查找用户信息
    let findUserInfo = await this.wxUserRepository.findOne({where:{openid: wx_user}})
    //查询所有关联此网红的人
    let findConcerns = await this.concernRepository.find({where:{concern_wx_user_id: findUserInfo.id}})
    //查询所有取消关联的网红
    let findUnConcerns = await this.unConcernRepository.find({where:{concern_wx_user: findUserInfo.openid}})
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //初始化用户名
      await this.wxUserRepository.createQueryBuilder(null,queryRunner).update({name:findUserInfo.initname, avatar_img: '', avatar_img_id: ''}).where({openid:wx_user}).execute()
      //修改为未认证
      await this.settingRepository.createQueryBuilder(null,queryRunner).update({value: value}).where({wx_user: wx_user, key: 'overseas'}).execute()
      //创建关联此网红的人的关联记录
      let unConcernsList = []
      findConcerns.filter(e => {
        return findUnConcerns.find(c => c.name == findUserInfo.name && c.wx_user == e.wx_user) ? false : true
      }).map(e => {
        let unconcern = new UnConcern()
        unconcern.name = findUserInfo.name
        unconcern.create_time = new Date()
        unconcern.concern_wx_user = findUserInfo.openid
        unconcern.wx_user = e.wx_user
        unConcernsList.push(unconcern)
      })
      if(unConcernsList.length > 0){
        await this.unConcernRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(UnConcern)
          .values(unConcernsList)
          .execute()
      }
      //删除所有关联此网红的人
      await this.concernRepository.createQueryBuilder(null, queryRunner).delete().where({concern_wx_user_id:findUserInfo.id}).execute()
      //删除精简版/正式版信息
      await this.settingRepository.createQueryBuilder(null, queryRunner).delete().where({wx_user: wx_user, key: 'clientVersion'}).execute()
      
      if(wx_user != system_wx_user){
        //删除用户的id_card
        await this.wxUserRepository.createQueryBuilder(null, queryRunner)
          .update({id_card: null})
          .where({openid: wx_user})
          .execute()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async getIsSwitchOverseas(wx_user: string){
    let findOverseas = await this.findOne_by_key(wx_user, 'overseas')
    let overseas = false //0 国内 1 海外
    if(findOverseas){
      overseas = findOverseas.value == '0' ? false : true
    }
    return overseas
    // let findVideo = await this.videoRepository.findOne({where:{wx_user: wx_user, check: 1, overseas: overseas}})
    // if(findVideo){
    //   return false
    // } else{
    //   return true
  }

  async get_isvideo(wx_user: string, overseas: number){
    let findVideo = []
    //非认证
    if(overseas == 0){
      findVideo = await this.videoRepository.query(`
        select * from video
        where video.overseas = 3 and video.wx_user = ? and ((video.profit_type = 0 and ic_group is not null) or video.profit_type = 1) and video.delete_tag = 0
      `,[wx_user])
    }else{
      findVideo = await this.videoRepository.query(`
        select * from video
        where video.overseas = 1 and video.wx_user = ? and ic_group is not null
      `,[wx_user])
    }
    if(findVideo.length > 0){
      return true
    }else{
      return false
    }
  }

  async setSetting(wx_user: string, key: string, value: any){
    let userSetting = new UserSetting()
    userSetting.wx_user = wx_user
    userSetting.key = key
    userSetting.value = value
    let findItem = await this.settingRepository.findOne({where:{wx_user: wx_user, key: key}})
    if(findItem){
      userSetting.id = findItem.id
    }
    return this.settingRepository.save(userSetting)
  }
}
